/**
 * Filename: ToastUtils.java
 * @author  Firefly
 * @contact postfirefly@163.com
 * @time    2016/2/23 16:36 
 */
package com.github.postsanf.yinian.utils;

import android.content.Context;
import android.support.annotation.StringRes;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Toast;

import com.github.postsanf.yinian.R;


public class ToastUtils {
	private static Toast mToast;

	//自定义显示Toast方式
	public static void showToast(Context context, CharSequence text, int duration) {
		if(mToast == null) {
			mToast = Toast.makeText(context, text, duration);
		} else {
			mToast.setText(text);
			mToast.setDuration(duration);
		}

		View view = mToast.getView();
		Animation anim = AnimationUtils.loadAnimation(context, R.anim.yn_anim_toast);
		view.setAnimation(anim);
		view.setBackgroundResource(R.drawable.yn_bg_toast);
		mToast.setView(view);
		mToast.setGravity(Gravity.BOTTOM , 0, 80);
		mToast.show();
	}


	private static final String TAG = ToastUtils.class.getSimpleName();
	private static Context sContext;
	private static Toast sToast;

	public static void cancel() {
		if (sToast != null) {
			sToast.cancel();
		}
	}

	public static void init(Context context) {
		sContext = context;
	}

	public static void show(CharSequence text) {
		if (sContext == null) {
			Log.e(TAG, "uninitialized");
			return;
		}
		if (TextUtils.isEmpty(text)) {
			Log.e(TAG, "is empty");
			return;
		}
		int duration = text.length() > 5 ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT;
		if (sToast == null) {
			sToast = Toast.makeText(sContext, text, duration);
		} else {
			sToast.setDuration(duration);
			sToast.setText(text);
		}
		sToast.show();
	}

	public static void show(@StringRes int resId) {
		if (sContext == null) {
			Log.e(TAG, "uninitialized");
			return;
		}
		show(sContext.getText(resId));
	}
}
